/**
 * 
 */
package com.flashdeck.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;

import com.flashdeck.domain.Card;
import com.flashdeck.domain.Deck;
import com.flashdeck.domain.DeckInfo;

/**
 * @author Vincentas
 *
 */
public class DeckHandler extends HandlerBase {

	private StringBuilder stringBuilder = new StringBuilder();
	
	private Deck deck;
	
	private DeckInfo deckInfo;
	
	private Set<Card> cards;
	
	private Card card;
	
	private static final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
	
	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		super.characters(ch, start, length);
		stringBuilder.append(ch, start, length);
	}
	
	private String getText() {
		String result = StringUtils.strip(stringBuilder.toString());
		stringBuilder.setLength(0);
		return result;
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#endElement(java.lang.String)
	 */
	@Override
	public void endElement(String name) throws SAXException {		
		if (name.equalsIgnoreCase("name")) {
			deckInfo.setName(getText());
		} else if (name.equalsIgnoreCase("description")) {
			deckInfo.setDescription(getText());
		} else if (name.equalsIgnoreCase("front")) {
			card.setFront(getText());
		} else if (name.equalsIgnoreCase("back")) {
			card.setBack(getText());
		} else if (name.equalsIgnoreCase("card")) {
			cards.add(card);
		} else if (name.equalsIgnoreCase("id")) {
			deckInfo.setId(getText());
		} else if (name.equals("deck")) {
			deckInfo.setCardCount(cards.size());
		}
	}
	
	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#startDocument()
	 */
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		
		deckInfo = new DeckInfo();
		deck = new Deck();	
		cards = new HashSet<Card>();	
		deck.setDeckInfo(deckInfo);
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#startElement(java.lang.String, org.xml.sax.AttributeList)
	 */
	@Override
	public void startElement(String name, AttributeList attributes)	throws SAXException {
		if (name.equalsIgnoreCase("card")) {
			card = new Card();
			card.setId(attributes.getValue("id"));
		} if (name.equalsIgnoreCase("deck")) {
			deckInfo.setId(attributes.getValue("id"));
		}
	}
	
	private Deck getDeck() {
		deck.setCards(cards);
		deck.setDeckInfo(deckInfo);
		
		return deck;
	}	
	
	private DeckInfo getDeckInfo() {
		return deckInfo;
	}

	public static DeckInfo parseDeckInfo(File file) {
		return getDeckHandler(file).getDeckInfo();
	}

	public static Deck parseDeck(File file) {
		return getDeckHandler(file).getDeck();
	}

	private static DeckHandler getDeckHandler(File file) {
		DeckHandler deckHandler = new DeckHandler();
		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			ZipInputStream zis = null;
			try {
				zis = new ZipInputStream(fis);
				
				ZipEntry nextEntry;
				while ((nextEntry = zis.getNextEntry()) != null && zis.available() > 0) {
					System.out.println(nextEntry.getName());
					if (nextEntry.getName().equalsIgnoreCase("deck.xml")) {						
						SAXParser parser = parserFactory.newSAXParser();
						
						InputStream is = new InputStreamLimit(zis, nextEntry.getSize());
						parser.parse(is, deckHandler);
						break;
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} finally {
				IOUtils.closeQuietly(zis);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(fis);
		}
		
		return deckHandler;
	}	
}
